<template>
  <div
    class="desktop-icon"
    :class="{ selected: isSelected }"
    :style="{ left: icon.x + 'px', top: icon.y + 'px' }"
    @click="handleClick"
    @dblclick="handleDoubleClick"
    @mousedown="handleMouseDown"
    @contextmenu.prevent.stop="$emit('contextmenu', icon, $event)"
  >
    <div class="icon-image" :style="{ background: icon.color }">
      <el-icon :size="32">
        <component :is="icon.icon" />
      </el-icon>
    </div>
    <div class="icon-label">{{ icon.label }}</div>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const props = defineProps({
  icon: {
    type: Object,
    required: true
  },
  isSelected: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['select', 'open', 'dragstart', 'contextmenu'])

// 拖拽相关状态
const isDragging = ref(false)
const startX = ref(0)
const startY = ref(0)
const dragThreshold = 5 // 移动超过5px才认为是拖拽

const handleClick = (event) => {
  if (!isDragging.value) {
    emit('select', props.icon.id, event)
  }
}

const handleDoubleClick = (event) => {
  if (!isDragging.value) {
    event.preventDefault()
    event.stopPropagation()
    emit('open', props.icon)
  }
}

const handleMouseDown = (event) => {
  if (event.button !== 0) return // 只响应左键
  
  isDragging.value = false
  startX.value = event.clientX
  startY.value = event.clientY

  const handleMouseMove = (e) => {
    const deltaX = Math.abs(e.clientX - startX.value)
    const deltaY = Math.abs(e.clientY - startY.value)
    
    // 如果移动距离超过阈值，开始拖拽
    if (deltaX > dragThreshold || deltaY > dragThreshold) {
      if (!isDragging.value) {
        isDragging.value = true
        emit('dragstart', props.icon, event)
      }
    }
  }

  const handleMouseUp = () => {
    document.removeEventListener('mousemove', handleMouseMove)
    document.removeEventListener('mouseup', handleMouseUp)
    // 延迟重置拖拽状态，避免影响双击
    setTimeout(() => {
      isDragging.value = false
    }, 100)
  }

  document.addEventListener('mousemove', handleMouseMove)
  document.addEventListener('mouseup', handleMouseUp)
}
</script>

<style scoped>
.desktop-icon {
  position: absolute;
  width: 90px;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 8px;
  cursor: pointer;
  border-radius: 4px;
  transition: background 0.2s;
}

.desktop-icon:hover {
  background: rgba(255, 255, 255, 0.1);
}

.desktop-icon.selected {
  background: rgba(255, 255, 255, 0.2);
}

.icon-image {
  width: 56px;
  height: 56px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  margin-bottom: 6px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.icon-label {
  font-size: 12px;
  color: white;
  text-align: center;
  text-shadow: 0 1px 3px rgba(0, 0, 0, 0.8);
  word-wrap: break-word;
  max-width: 100%;
  line-height: 1.3;
}
</style>

